package cn.sytton.taffe.monitor.controller;

import cn.hutool.core.date.DateUtil;
import cn.sytton.taffe.framework.constants.RedisKey;
import cn.sytton.taffe.framework.factory.RedisUtil;
import cn.sytton.taffe.framework.security.entity.LoginUser;
import cn.sytton.taffe.framework.security.jwt.JwtFactory;
import cn.sytton.taffe.monitor.model.OnlineUser;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * 在线用户监控控制层
 *
 * @author skyrock
 */
@Tag(name = "在线用户监控")
@RestController
@RequestMapping("/monitor/online")
public class OnlineController {

    @Resource
    private JwtFactory jwtFactory;

    @Resource
    private RedisUtil redisUtil;

    @Operation(summary = "获取在线用户")
    @Parameter(name = "params", in = ParameterIn.QUERY, required = true)
    @GetMapping
    public List<OnlineUser> findOnlineUser(OnlineUser params) {
        List<OnlineUser> users = new ArrayList<>();
        Collection<String> keys = redisUtil.keys(RedisKey.LOGIN_TOKEN_ID_KEY+"*");
        for(String key : keys) {
            LoginUser loginUser = redisUtil.getObject(key, LoginUser.class);
            if (StringUtils.hasText(params.getLoginName()) && !loginUser.getLoginName().contains(params.getLoginName())) {
                continue;
            }
            if (StringUtils.hasText(params.getUserName()) && !loginUser.getUserName().contains(params.getUserName())) {
                continue;
            }
            if (StringUtils.hasText(params.getIp()) && !loginUser.getIp().contains(params.getIp())) {
                continue;
            }
            if (params.getLoginTime() != null && !DateUtil.formatDate(params.getLoginTime()).equals(DateUtil.formatDate(loginUser.getLoginTime()))) {
                continue;
            }
            users.add(new OnlineUser(loginUser));
        }
        return users;
    }

    @Operation(summary = "强退登录账号")
    @Parameter(name = "token", description = "token", in = ParameterIn.PATH, required = true)
    @PostMapping("/logout/{token}")
    public void logoutOnlineUser(@PathVariable String token) {
        jwtFactory.delLoginUser(token);
    }
}
